/*
 * @Author: yuki
 * @Date: 2025-11-06 15:29:13
 * @LastEditTime: 2025-11-06 16:29:47
 * @Description: 用户模块服务
 */
import { User } from '@horoscope/shared';
import { Injectable } from '@nestjs/common';

import { UserModel } from 'generated/prisma/models/User';

import { DataMismatchException } from '@/exception';
import { PrismaService } from '@/share/prisma.service';

@Injectable()
export class UserService {
  constructor(private readonly prisma: PrismaService) {}

  async getUserInfoById(id: number): Promise<User.IUserInfo> {
    const userInfo = await this.prisma.user.findUnique({
      where: {
        id: id
      }
    });
    if (!userInfo) {
      throw new DataMismatchException('用户不存在');
    }
    return this.formatUserInfo(userInfo);
  }

  async getUserInfoByUsername(username: string): Promise<User.IUserInfo> {
    const userInfo = await this.prisma.user.findUnique({
      where: {
        userName: username
      }
    });
    if (!userInfo) {
      throw new DataMismatchException('用户不存在');
    }
    return this.formatUserInfo(userInfo);
  }

  formatUserInfo(userInfo: UserModel): User.IUserInfo {
    return {
      id: userInfo.id,
      userId: userInfo.userId.toString(),
      userName: userInfo.userName,
      email: userInfo.email,
      avatar: userInfo.avatar,
      phone: userInfo.phone,
      createTime: userInfo.createTime.toISOString()
    };
  }

  async checkUserExistsByUsername(username: string): Promise<boolean> {
    const userInfo = await this.prisma.user.findUnique({
      where: {
        userName: username
      },
      select: { id: true }
    });
    return !!userInfo;
  }

  async checkUserExistsById(id: number): Promise<boolean> {
    const userInfo = await this.prisma.user.findUnique({
      where: {
        id: id
      },
      select: { id: true }
    });
    return !!userInfo;
  }
}
